
export default {
    state: {
        list:JSON.parse(localStorage.getItem('cart')) || [],
    },
    getters: {
        cartTotal:state=>{ // 购物车商品总数
            let num = 0
            state.list.forEach(v=>{
                num += v.cartCount
            })
            return num
        },
        total:state => { // 购物车商品总价
            return state.list.reduce((total,item)=>
                 total + item.price * item.cartCount,0
            )
        }
        },

    mutations: {
        // 添加商品到购物车
        addCart(state,item){
            // console.log(item);
            
            const good = state.list.find(v=>v.title == item.title)
            // console.log(good);
            
            if(good){
                good.cartCount += 1
            }else{
                state.list.push({
                    ...item,
                    cartCount:1
                })
            }
            // console.log(state.list);
            
        },
        cartremove(state,index){
            if(state.list[index].cartCount > 1){
                state.list[index].cartCount -= 1
            }            
        },
        cartadd(state,index){
            state.list[index].cartCount += 1
        }
    },
    
}